<template>
  <el-row type="flex" justify="center">
    <el-col :span="19">
      <h2>{{ channelName }}</h2>
      <loading v-show="isLoading"></loading>
      <news-list :news="news" v-show="!isLoading"></news-list>
      <pager :total="total" :page="page" :limit="limit" @pageChange="handleChange"></pager>
    </el-col>
  </el-row>
</template>

<script>
import Pager from "../components/Pager";
import Loading from '../components/Loading'
import NewsList from "../components/NewsList";
import * as newsServices from "../services/newsServices";
import router from "../router";

export default {
  name: "ChannelNews",
  components: {
    Pager, Loading, NewsList
  },
  data() {
    return {
      total: 0, //总记录
      // page: 1, //当前页
      limit: 3, //每页显示几条数据
      news: [],
      isLoading: true,
      // channelName: ''
    }
  },
  methods: {
    handleChange(newPage) {
      // 在代码中实现 page=1,2 的跳转，使用命令式导航
      // 方法一
      // router.push('?page='+newPage)
      // 方法二
      router.push({
        name: 'channel',
        params: {
          id: this.$route.params.id
        },
        query: {
          page: newPage
        }
      })

      // this.page = newPage;
      this.getNews();
    },
    //设置频道名称
    // async setChannelName() {
    //     let channels = await newsServices.getChannelList();
    //     // typeof this.$route.params.id 第一次的值为string，所以判断时需转为number
    //     let channel = channels.find((item) => item.id === Number(this.$route.params.id));
    //     this.channelName = channel.name;
    // },
    // 获取数据
    async getNews() {
      // 限制路由参数
      if (this.$route.params.id > 10 || isNaN(this.$route.params.id)) {
        this.$route.params.id = 1;
      }
      this.isLoading = true;
      this.news = [];
      let resp = await newsServices.getNewsList(this.$route.params.id, this.page, this.limit);
      this.news = resp.data.data;
      this.total = resp.data.total;
      this.isLoading = false;


    },
  },

  // 计算属性
  computed: {
    page() {
      return Number(this.$route.query.page) || 1;
    },
    channelName() {
      let channels = this.$store.state.channels.data;
      if (channels.length > 0) {
        let channel = channels.find((item) => item.id == this.$route.params.id)
        return channel.name
      }
      return '';
    }
  },

  // 监控方法，当组件中的数据发生改变，会触发
  watch: {
    "$route.params.id": {
      immediate: true, // immediate开启首次赋值监听
      handler() {
        // console.log(this.$route)
        // this.page = 1;
        // this.setChannelName();
        this.getNews();
      },
    }
  }

}
</script>

<style scoped lang="scss">
@import "../assets/css/index.scss";

h2 {
  color: $primary-title-color;
  padding-bottom: 5px;
  border-bottom: 3px solid $first-border-color;
}
</style>
